package org.artifact.core.lang;

import java.util.LinkedHashMap;
import java.util.Map;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

/**
 * 插件
 * 
 * @author apple
 *
 */
@SuppressWarnings("unchecked")
public class Plugins {

	static final Log log = LogFactory.get(Plugins.class);

	private final Map<String, IPlugin> plugins = new LinkedHashMap<>();

	
	/** 添加插件 */
	public Plugins add(IPluginFactory factory) {
		IPlugin plugin = factory.create();
		if (plugin == null) {
			throw new IllegalArgumentException("plugin can not be null");
		}
		String pluginKey = plugin.getClass().getName();
		if (pluginKey == null) {
			throw new IllegalArgumentException("plugin name can not be null");
		}
		if (plugins.containsKey(pluginKey)) {
			throw new IllegalArgumentException("this plugin name existed"); 
		}
		plugins.put(pluginKey, plugin);
		return this;
	}
	
	public <T> T getIPlugin(Class<T> clazz){
		return (T) plugins.get(clazz.getName());
	}
	
	
	public void start() {
		if (plugins.isEmpty()) {
			return;
		}
		plugins.forEach((k, v) -> {
			try {
				boolean status = v.start();
				if (!status) {
					String msg = "Start Plugin [" + k + "] Error";
					throw new RuntimeException(msg);
				}
			} catch (Exception e) {
				String msg = "Start Plugin [" + k + "] Error";
				throw new RuntimeException(msg);
			}
		});
	}
	
	public void stop() {
		if (plugins.isEmpty()) {
			return;
		}
		plugins.forEach((k, v) -> {
			try {
				boolean status = v.stop();
				if (!status) {
					String msg = "Stop Plugin [" + k + "] Error";
					throw new RuntimeException(msg);
				}
			} catch (Exception e) {
				String msg = "Stop Plugin [" + k + "] Error";
				throw new RuntimeException(msg);
			}
		});
	}
}
